import { h, Component } from 'preact';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import Modal from '~/components/Modal';
import Loading from '~/components/Loading';
import {tpl1, tpl2, tpl3, tpl4, tpl5, menulist} from './tplData';
import s from './Tpl.scss';
import tp1 from './1.png';
import fc from './face.jpg';
import cl from './cl.png';


export default class Tpl extends Component {
	constructor(props) {
		super(props);
		this.state = {
			showBar: true,
			newimg: null,
			scale: false,
			buildOk: false,
			buildOkBtn: false,
			showResult: null,
			selectedId: 1,
			Loadingbox: false,
			menulist
		};
		this.container = null;
	}

	toggleShowBar = () => {
		this.setState({
			showBar: !this.state.showBar
		});
	}

	toggleBuildOkBtn = () => {
		this.setState({
			buildOkBtn: !this.state.buildOkBtn
		});
	}

	getJobTitle = (code) => {
		switch (code) {
			case '0':
				return '水台';
			case '1':
				return '配菜';
			case '2':
				return '打荷';
			case '3':
				return '砧板';
			case '4':
				return '上杂';
			case '5':
				return '油鸡';
			case '6':
				return '尾锅';
			case '7':
				return '五锅';
			case '8':
				return '四锅';
			case '9':
				return '三锅';
			case '10':
				return '二锅';
			case '11':
				return '头锅';
			case '12':
				return '总厨';
			case '13':
				return '顾问';
			case '14':
				return '其他';
		}
	}
        //获取像素密度
	getPixelRatio = (context) =>{
		let backingStore = context.backingStorePixelRatio ||
                    context.webkitBackingStorePixelRatio ||
                    context.mozBackingStorePixelRatio ||
                    context.msBackingStorePixelRatio ||
                    context.oBackingStorePixelRatio ||
                    context.backingStorePixelRatio || 1;
		return (window.devicePixelRatio || 1) / backingStore;
	}
        //绘制dom 元素，生成截图canvas
	html2Canvas = () => {
		Loading.show();
		const _this = this;
		let shareContent = this.reftag;// 需要绘制的部分的 (原生）dom 对象 ，注意容器的宽度不要使用百分比，使用固定宽度，避免缩放问题
		let width = shareContent.offsetWidth;  // 获取(原生）dom 宽度
		let height = shareContent.offsetHeight; // 获取(原生）dom 高
		let offsetTop = shareContent.offsetTop;  //元素距离顶部的偏移量

		let canvas = document.createElement('canvas');  //创建canvas 对象
		let context = canvas.getContext('2d');
		let scaleBy = 2;  //获取像素密度的方法 (也可以采用自定义缩放比例)
		canvas.width = width * scaleBy;   //这里 由于绘制的dom 为固定宽度，居中，所以没有偏移
		canvas.height = (height + offsetTop) * scaleBy;  // 注意高度问题，由于顶部有个距离所以要加上顶部的距离，解决图像高度偏移问题
		context.scale(scaleBy, scaleBy);
		console.log('width', width);
		console.log('height', height + 35);
		let opts = {
			allowTaint:true,//允许加载跨域的图片
			tainttest:true, //检测每张图片都已经加载完成
			scale:scaleBy, // 添加的scale 参数
			canvas, //自定义 canvas
			logging: true, //日志开关，发布的时候记得改成false
			width, //dom 原始宽度
			height //dom 原始高度
		};

		window.html2canvas(shareContent, opts).then((canvas) => {
			Loading.hide();
			_this.setState({
				newimg: canvas.toDataURL("image/png"),
				buildOk: true,
				showBar: false,
				showResult: '名片已生成,请长按图片保存'
			});
		});
	}


	handlerGenerate = () => {
		this.html2Canvas();
	}

	handlerRebuild = () => {
		this.initBuild();
	}

	initBuild = () => {
		this.setState({
			newimg: null,
			buildOk: false,
			showBar: true,
			showResult: null,
			buildOkBtn: false
		});
	}

	handleHide = () => {
		this.setState({
			showResult: null,
			buildOkBtn: true
		});
	}

	handlerBack = () => {
		this.initBuild();
		this.props.action();
	}

	handlerSelectTpl = () => {
		const {user, code} = this.props;
		const index = this.state.selectedId;
		let codeUrl;
		if (code) {
			codeUrl = `data:image/png;base64,${code}`;
		} else {
			codeUrl = cl;
		}
		switch (index) {
			case 1:
				return tpl1(user.points ? user.points : 8.5, user.name, user.company, this.getJobTitle(user.jobTitle), codeUrl, user.phone, user.headimgurl||fc);
			case 2:
				return tpl2(user.points ? user.points : 8.5, user.name, user.company, this.getJobTitle(user.jobTitle), codeUrl, user.phone, user.headimgurl||fc);
			case 3:
				return tpl3(user.points ? user.points : 8.5, user.name, user.company, this.getJobTitle(user.jobTitle), codeUrl, user.phone, user.headimgurl||fc);
			case 4:
				return tpl4(user.points ? user.points : 8.5, user.name, user.company, this.getJobTitle(user.jobTitle), codeUrl, user.phone, user.headimgurl||fc);
			case 5:
				return tpl5(user.points ? user.points : 8.5, user.name, user.company, this.getJobTitle(user.jobTitle), codeUrl, user.phone, user.headimgurl||fc);
			default:
				return tpl1(user.points ? user.points : 8.5, user.name, user.company, this.getJobTitle(user.jobTitle), codeUrl, user.phone, user.headimgurl||fc);
		}
	}

	handlerChangeIndex = (index) => () => {
		Loading.show();
		this.setState({
			Loadingbox: true,
			selectedId: index
		});
		window.setTimeout(() => {
			Loading.hide();
			this.setState({
				Loadingbox: false
			});
		}, 1500);
	}

	render() {
		const {user, code} = this.props;
		const { newimg, Loadingbox, showBar, buildOk, showResult, buildOkBtn, menulist, selectedId } = this.state;
		return (
			<div className={classNames(s.root, s.noselect, this.props.visible ? 'show' : 'hide')}>

				<div className={s.generate} id="img" ref={(ref) => {this.refImg = ref;} }>
				{
					buildOk ? <img src={this.state.newimg} onClick={this.toggleBuildOkBtn} alt=""/> : null
				}
				</div>

				<div className={classNames(s.tpl)} onClick={this.toggleShowBar} ref={(ref) => {this.reftag = ref;} }>
					{this.handlerSelectTpl(2)}
				</div>
				{
					showBar ?
					<div className={classNames(s.tapbox, 'shadow-top')}>
						<div className={classNames(s.bar, 'w8 center al-c')}>
							{
								menulist.map((item) => <div
								key={item.id}
								className={classNames(selectedId === item.id ? 'orangered' : null)}
								onClick={this.handlerChangeIndex(item.id)}>
									{item.name}
								</div>)
							}
						</div>
						<div className="al-c gray font-small">（轻触屏幕预览模版）</div>
						<div className="w8 center mgt1 clear-fix">
							<div className="w4-5 fl btn" onClick={this.handlerGenerate}>生成名片</div>
							<div className="w4-5 fr btn" onClick={this.handlerBack}>返回</div>
						</div>
					</div> :
					null
				}
				{
					buildOk ?
					<div className={classNames(s.buildOkbar, 'ww')}>
						{buildOkBtn ? <div className="center w9 clearfix">
							<div className="w4-5 fl btn" onClick={this.handlerRebuild}>重新生成</div>
							<div className="w4-5 fr btn" onClick={this.handlerBack}>返回</div>
						</div> : null}
					</div> :
					null
				}
				<Modal
					contentLabel="ModalE"
					isOpen={showResult ? true : false}
					onRequestClose={this.handleHide}
					shouldCloseOnOverlayClick={true}
				>
					<div  className="pdt3 pdb2 al-c">
					{ showResult }
					</div>
					<div className="pdb2">
						<div className="w4-5 center btn" onClick={this.handleHide}>确定</div>
					</div>
				</Modal>
				{Loadingbox ? <div className={s.loadingbox}></div> : null}
			</div>
		);
	}
}
